﻿using GamovMvc.Framework.Control;
using GamovMvc.Framework.Request;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace GamovMvc.Web.Controller
{
    public abstract class BaseController : IController
    {

        protected HttpContext Context { get; set; }

        protected IDictionary<string, object> RouteData { get; set; }

        public ActionResult Execute(RequestContext context)
        {
            this.Context = context.HttpContext;
            this.RouteData = context.RouteData;

            // 根据action的名字获取需要调用的方法名称
            var actionName = RouteData["action"].ToString();
            var methods = this.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            MethodInfo method = null;
            foreach (var item in methods)
            {
                if (item.Name.Equals(actionName, StringComparison.InvariantCultureIgnoreCase))
                {
                    method = item;
                    break;
                }
            }
            // 如果没有找到指定的action方法
            if (method == null)
            {
                throw new HttpException(404, "Not Found");
            }

            List<object> values = new List<object>();
            var parameters = method.GetParameters();

            foreach (var para in parameters)
            {
                var name = para.Name;
                var type = para.ParameterType;
                var value = Context.Request[name];
                if (string.IsNullOrEmpty(value))
                {
                    value = RouteData.ContainsKey(name) ? RouteData[name].ToString() : null;
                }
                values.Add(string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, type));
            }

            ActionResult  result = method.Invoke(this, values.ToArray()) as ActionResult;
            return result;
        }
    }
}